﻿using System;
using System.Configuration;
using System.Data;
using System.Web.Services.Protocols;
using HelpdeskServices.IntegrationServices;
using HelpdeskServices.CrmWebReference;
using HelpdeskServices.Properties;

public class CrmCase
{
    private Lookup _caseSubject;
    private Guid _crmIncedentId;
    private Customer _customer;
    private Guid _customerId;
    private string _description;
    private int _new_KalahariWebSiteReference;
    private int _new_OrderNumber;
    private Email _sourceEmail;
    private WebCase _webCase;
    private CrmDateTime _emailReceivedOn;

    public int new_KalahariWebSiteReference
    {
        get { return _new_KalahariWebSiteReference; }
        set { _new_KalahariWebSiteReference = value; }
    }
    public int new_OrderNumber
    {
        get { return _new_OrderNumber; }
        set { _new_OrderNumber = value; }
    }
    public Guid CustomerId
    {
        get { return _customerId; }
        set { _customerId = value; }
    }
    public Email SourceEmail
    {
        get { return _sourceEmail; }
        set { _sourceEmail = value; }
    }
    public Guid IncedentId
    {
        get { return _crmIncedentId; }
        set { _crmIncedentId = value; }
    }

    public string Description
    {
        get { return _description; }
    }

    /// <summary>
    /// CreateInCrm this case in MS CRM
    /// </summary>
    public void Create(WebCase WebCase)
    {
        _webCase = WebCase;
    }

    public void Create()
    {
        if(_webCase == null)
        {
            InitialiseEmailImportValues();
        }
        else
        {
            InitialiseWebCaseImportValues();
        }
        
        CreateCrmIncedent();
    }
    private void CreateCrmIncedent()
    {
        incident incident = new incident();
        incident.customerid = _customer;
        incident.subjectid = _caseSubject;
        incident.description = _sourceEmail.ToString();
        incident.new_ordernumber = _new_OrderNumber.ToString();
        incident.title = String.Concat(Resources.EmailSubjectPrefix, _sourceEmail.Subject);
        incident.new_importedemailsenton = _emailReceivedOn;

        CrmService crmProxyService = Common.CrmWebServiceProxy();
        Guid incidentId = crmProxyService.Create(incident);
        IncedentId = incidentId;
        return;
    }


    private void InitialiseEmailImportValues()
    {
        _caseSubject = GetSubjectIdForCreatingCasesFromEmail();
        _customer = getCustomer(_sourceEmail);
        _description = _sourceEmail.ToString();
        _new_OrderNumber = _sourceEmail.OrderNumber;
        _emailReceivedOn = _sourceEmail.ReceivedOn;
    }
    private static Lookup GetSubjectIdForCreatingCasesFromEmail()
    {
        Guid SubectId = new Guid(ConfigurationManager.AppSettings["ConvertEmailSubjectId"]);
        Lookup lookupToReturn;
        lookupToReturn = CrmTypes.CreateLookup(EntityName.subject.ToString(), SubectId);
        return lookupToReturn;
    }
    private static Lookup GetSubjectIdForCreatingWebCases()
    {
       
        Guid SubectId = new Guid(ConfigurationManager.AppSettings["ImportWebCaseSubjectId"]);
        Lookup lookupToReturn = CrmTypes.CreateLookup(EntityName.subject.ToString(), SubectId);
        return lookupToReturn;
    }

    private void parseRowforCustomerId(DataRow row)
    {
        foreach (object cell in row.ItemArray)
        {
            if (Guid.Empty.Equals(_customerId))
            {
                switch (cell.ToString().Length)
                {
                    case 38:
                        _customerId = new Guid(cell.ToString());
                        break;
                    case 32:
                        Contact contact = new Contact();
                        contact.ShopperId = cell.ToString();
                        contact.CreateInCrm();
                        _customerId = contact.ContactIdInCrm;
                        break;
                }
            }
        }
    }
    /// <summary>
    /// Gets the customer.
    /// If the datarow does not contain rows, that means the search result was not sucessfull
    /// So we cant find it in CRM and we cant find it in KMS in that case we create a unknown contact.
    /// </summary>
    /// <param name="emailToGetCustomerFrom">The email to get customer from.</param>
    /// <returns></returns>
    private Customer getCustomer(Email emailToGetCustomerFrom)
    {
        CombinedSearch combinedSearch=new CombinedSearch();

        DataTable searchResultsForCustomer = combinedSearch.Search(emailToGetCustomerFrom.FromEmailAddress);
        if (searchResultsForCustomer.Rows.Count == 1)
        {
            foreach (DataRow row in searchResultsForCustomer.Rows)
            {
                parseRowforCustomerId(row);
            }
        }
        else
        {
            string UnknownContactFirstName = emailToGetCustomerFrom.FromEmailAddress;
            string UnknownContactLastName = Resources.UknownContactLastName;

            Contact unkownContact = new Contact();
            unkownContact.FirstName = UnknownContactFirstName;
            unkownContact.LastName = UnknownContactLastName;
            unkownContact.EmailAddress = emailToGetCustomerFrom.FromEmailAddress;
            unkownContact.CreateInCrmWhenUnknown();
            _customerId = unkownContact.ContactIdInCrm;
        }
        _customer = CrmTypes.CreateCustomer(EntityName.contact.ToString(), _customerId);
        return _customer;
    }
    private void InitialiseWebCaseImportValues()
    {
        _new_KalahariWebSiteReference = _webCase.CustomerFeedbackID;
        _caseSubject = GetSubjectIdForCreatingWebCases();
        _new_OrderNumber = _webCase.ShortOrderId;
        _emailReceivedOn = CrmTypes.CreateCrmDateTimeFromUniversal(DateTime.Now.ToUniversalTime());
    }
    public void attachEmail()
    {
        email email = new email();
        email.activityid = CrmTypes.CreateKey(_sourceEmail.EmailId);
        email.regardingobjectid = CrmTypes.CreateLookup(EntityName.incident.ToString(), _crmIncedentId);
        TargetUpdateEmail target = new TargetUpdateEmail();
        target.Email = email;

        UpdateRequest update = new UpdateRequest();
        update.Target = target;
        try
        {
            CrmService microsoftCrmWebService = Common.CrmWebServiceProxy();
            microsoftCrmWebService.Execute(update);
        }
        catch (SoapException soapError)
        {
            Common.LogErrorMessage(soapError);
        }
    }
    public void DetachEmailFromQueue()
    {
        DetachFromQueueEmailRequest request = new DetachFromQueueEmailRequest();
        request.EmailId = _sourceEmail.EmailId;
        request.QueueId = new Guid(ConfigurationManager.AppSettings[Resources.ConfigurationKeyForSupportQueueId].ToString());

        CrmService microsoftCrmWebService = Common.CrmWebServiceProxy();

        DetachFromQueueEmailResponse response = (DetachFromQueueEmailResponse) microsoftCrmWebService.Execute(request);
    }

}